<?php
Yii::import('dao.bidAuction.AuctionLimitDao');
Yii::import('application.components.autobid.*');
class CheckoutController extends Controller {

	public $layout='//layouts/default';
	
	public function accessRules()
	{
		return array(
// 				array('allow', // allow admin user to perform 'admin' and 'delete' actions
// 						'actions'=>array('index','cart','order','shipping','confirm'),
// 						'users'=>array('@'),
// 				),
// 				array('deny',  // deny all users
// 						'users'=>array('*'),
// 				),
		);
	}

    public function init(){
        parent::init();
//         if(Yii::app()->params['server_environment']=='live'){
            $this->https();
//         }
    }
	
	public function actionIndex(){
		//auction id,order type default 1
		$id = Yii::app()->request->getParam('id',null);
		$orderType = Yii::app()->request->getParam('orderType',1);
        if(empty($id)){
             Yii::app()->getRequest()->redirect(Yii::app()->baseUrl);
        }
		//初始化支付流程
		$paymentInfo = new PaymentInfo(array(
			new PaymentAuctions(),
		));
		if($orderType==2){
			$check=Yii::app()->runController('auctions/buyItNow/'.$id);
		}
		
		$paymentInfo->setPaymentCode(Payment::createPaymentCode(array('objId' => $id, 'customerId' => Yii::app()->user->id)));
		
		$return = $paymentInfo->auction->setAuctionId($id);

		if(!$return){
		    
			$this->redirect(Yii::app()->createUrl('.'));
		}	
		
		/*
		 *获取用户所花cash bid数目 
		 */
		$bidhistory=new BidHistory();
		$cashBidNum=$bidhistory->countBySql('
		    SELECT
            	COUNT(ab.id)
            FROM
            	auction_bid_log AS ab
            WHERE
            	ab.customer_id = '.Yii::app()->user->id.'
            AND ab.auction_id = '.$id.'
            AND ab.bid_type = "CASH"
		');
		
		if($orderType != 2){	//bid支付流程
			$paymentInfo->setPaymentData(new PaymentOrderInfo());	

			$orderInfo = $paymentInfo->orderInfo;
			
			$orderInfo->setOrders(Yii::app()->user->id,$id);
			
			
		}else{	//buy it now支付流程（还未优化）	
		    /**
		     * 关闭autobid
		     */
		    $customerId=Yii::app()->user->id;
		    $auctionLimit = new AuctionLimitDao();
		    $autobid=new AutoBidDao();
		    $auctionLimit->auctionId = $id;
		    $auctionLimit->customerId = $customerId;
		    $autobid->setPrimaryKey($id,$customerId);
		    $auctionLimit->deleteLimit(AuctionLimitDao::AUTO_BID_LIMIT);
		    $autobid->delAutoBid();
		    
			$paymentInfo->setPaymentData(new PaymentBuyItNow());
			$orderInfo = $paymentInfo->buyItNow;
			$orderInfo->scene = 'binexpire';
			$orderInfo->setOrders(Yii::app()->user->id,$id)->setCustomerId(Yii::app()->user->id)->setAuctionId($id);
            
			if(!$orderInfo->orderExistsVaild()){
                
				$orderInfo->setAuctionInfo($return)->setOrderInfoFromAuction(Yii::app()->user->id);
			}else{
				$orderInfo->setAuctionInfo($return)->setOrderInfoFromAuction(Yii::app()->user->id,$orderInfo->id);
            
			}
            
		}
		//订单验证
		if(!$paymentInfo->vaild()){		    
			$orderError = new OrderErrorLog();
			$orderError->customer_id 	= Yii::app()->user->id;
			$orderError->auction_id 	= $paymentInfo->auction->id;
			$orderError->created 		= time();
			$orderError->post_data 		= json_encode($paymentInfo->toArray());
			$orderError->error_message  = json_encode($paymentInfo->errorMessage());
			$orderError->url			= Yii::app()->request->getUrl();			
			$orderError->save(false);
			$this->redirect(Yii::app()->createUrl('.'));

		}
		
		$paymentInfo->saveCache();
        $resource=new AuctionResource();
        $resource_data=$resource->find("auction_id=".$paymentInfo->auction->auctionId." and resource_key= 'image_1'");
        if(!empty($resource_data)){                    
            $resource_img=new ResourceImg();
            $resource_img_data=$resource_img->findByPk($resource_data->resource_id);
            if(!empty($resource_img_data)){
                $image=$resource_img_data->path;
                
            }
            
        }
        else{
            $image = Yii::app()->baseUrl.'/images/no-image.png';
        }
		$paymentCode = $paymentInfo->getPaymentCode();
		$this->render('cart',array(
			'model' 		=> $paymentInfo->auction,
			'orderInfo' 	=> $orderInfo,
			'paymentCode' 	=> $paymentCode,
			'paymentInfo'	=> $paymentInfo,
		    'image'         => $image,
		    'auction_id'    => $id,
		    'cashBidNum'=>$cashBidNum
		));
	}
	
	public function actionShipping(){
		//通过支付码来获取订单信息
		$paymentCode = Yii::app()->request->getParam('paymentcode',null);
        $auction_id=Yii::app()->request->getParam('auction_id',null);
        
		$paymentInfo = new PaymentInfo();
		
		$paymentInfo->setPaymentCode($paymentCode);
		$paymentInfo->getCache();
        
		$auction_parame=new AuctionParame();
		$parame_data=$auction_parame->find("auction_id=".$auction_id." and parame_name='ffl'");
		if(!empty($parame_data)){
		    if($parame_data->parame_value==1){ 		    
    		    $model = new CustomerOrderShippingInfo();
    		    $customerinfo=new CustomerInfo();
    		    $customerinfo_data=$customerinfo->find('customer_id='.Yii::app()->user->id);
    		    $this->render('shipping_ffl',array(
    		        'model'	=> $model,
    		        'paymentCode' => $paymentCode,
    		        'customerinfo'=> $customerinfo_data,      
    		    ));
    		}else{
        		$model = CustomerOrderShippingInfo::model()->find('t.customer_id = '.Yii::app()->user->id);
        		if(empty($model)){
        			$model = new CustomerOrderShippingInfo();
        		}else{
        			Yii::app()->session['customerShippingInfo'] = $model->attributes;
        		}
        
        		$this->render('shipping',array(
        			'model'	=> $model,	
        			'paymentCode' => $paymentCode,
        		    'checkFfl' =>$parame_data->parame_value,
        		));
    		}
	    }else{
	        Yii::app()->getRequest()->redirect(Yii::app()->baseUrl);
	    }
	}
	
	public function actionOrder(){
		//通过支付码来获取订单信息
		$paymentCode = Yii::app()->request->getParam('paymentcode',null);
		$paymentInfo = new PaymentInfo();
		$paymentInfo->setPaymentCode($paymentCode);
		$paymentInfo->getCache();

		//订单验证
		if(!$paymentInfo->vaild()){			

			$orderError = new OrderErrorLog();
			$orderError->customer_id 	= Yii::app()->user->id;
			$orderError->auction_id 	= $paymentInfo->auction->id;
			$orderError->created 		= time();
			$orderError->post_data 		= json_encode($paymentInfo->toArray());
			$orderError->error_message  = json_encode($paymentInfo->errorMessage());
			$orderError->url			= Yii::app()->request->getUrl();
			$orderError->save(false);
			$this->redirect(Yii::app()->createUrl('.'));
		}

		if(is_object($paymentInfo->orderInfo)){
			$orderInfo = $paymentInfo->orderInfo;
		}
		if(is_object($paymentInfo->buyItNow)){
			$paymentInfo->buyItNow->setAuctionInfo($paymentInfo->auction);
			$orderInfo = $paymentInfo->buyItNow;
		}

		if(!empty($_POST['CustomerOrderShippingInfo'])){
		    $paymentInfo->setPaymentData(new PaymentShipping());

			if(is_object($paymentInfo->buyItNow)){
				$tax_fee = 0;
				if("2123"==$_POST['CustomerOrderShippingInfo']["shipping_state"]){
					$auctionId = $paymentInfo->auction->auctionId;
					$tax_model = AuctionParame::model()->find("auction_id={$auctionId} AND parame_name='tax'");
					$tax = null!=$tax_model ? $tax_model->parame_value:0;
					if(1==$tax){
						$retail_price = $paymentInfo->auction->value_price;
						$shipping_price = $paymentInfo->auction->cost;
						$tax_fee =  bcadd(0,0.06*bcadd($retail_price,$shipping_price,2),2);
					}
				}

				$total_price_old = $paymentInfo->buyItNow->total_price;
				$old_tax_fee = $paymentInfo->buyItNow->tax_fee;
				$total_price = bcsub($total_price_old,$old_tax_fee,2);
				$paymentInfo->buyItNow->tax_fee = $tax_fee;
				$paymentInfo->buyItNow->total_price = bcadd($tax_fee,$total_price,2);
				$paymentInfo->buyItNow->_orderAr->total_price = bcadd($tax_fee,$total_price,2);
				$paymentInfo->buyItNow->_orderAr->tax_fee = $tax_fee;
			}
		    if(!empty($_POST['ffl'])){
		        $paymentInfo->shippingInfo->setShippingInfo($_POST['CustomerOrderShippingInfo']);
		    }else{
		        $paymentInfo->shippingInfo->setShipping(Yii::app()->user->id);

// 		        $get_ffl=
		        $paymentInfo->shippingInfo->setShippingInfo($_POST['CustomerOrderShippingInfo']);
		        // 			$buyAuction = new PaymentBuyAuction();
		        // 			$buyAuction->ffl=$get_ffl->ffl;
		        // 			Yii::app()->cache->set('ffl'.Yii::app()->user->id,$get_ffl->ffl);
		        $a=$paymentInfo->shippingInfo->saveInfo();

		    }
		    $shippingInfo = $paymentInfo->toArray();
		    if(!empty($shippingInfo['id'])){
		        $paymentInfo->shippingInfo->setShipping(Yii::app()->user->id);
		    }
		}

		$paymentInfo->saveCache();
		
		//get billing info
		$billingInfo = CustomerOrderBillingInfo::model()->find('customer_id = '.Yii::app()->user->id);
		if(empty($billingInfo)){
			$billingInfo = new CustomerOrderBillingInfo();
		}
		$resource=new AuctionResource();
		$resource_data=$resource->find("auction_id=".$paymentInfo->auction->auctionId." and resource_key= 'image_1'");
		if(!empty($resource_data)){
		    $resource_img=new ResourceImg();
		    $resource_img_data=$resource_img->findByPk($resource_data->resource_id);
		    if(!empty($resource_img_data)){
		        $image=$resource_img_data->path;
		
		    }
		
		}
		else{
		    $image = Yii::app()->baseUrl.'/images/no-image.png';
		}
		
		/*
		 *获取用户所花cash bid数目
		 */
		$bidhistory=new BidHistory();
		$cashBidNum=$bidhistory->countBySql('
		    SELECT
            	COUNT(ab.id)
            FROM
            	auction_bid_log AS ab
            WHERE
            	ab.customer_id = '.Yii::app()->user->id.'
            AND ab.auction_id = '.$paymentInfo->auction->id.'
            AND ab.bid_type = "CASH"
		');
		
		$this->render('order',array(
			'shippingInfo'		=>		$paymentInfo->shippingInfo,
			'auctionsInfo'		=>    	$paymentInfo->auction,
			'orderInfo'			=>      $orderInfo,
			'billingInfo'		=>		$billingInfo,
			'paymentCode'		=>		$paymentCode,
			'paymentInfo'		=>		$paymentInfo,
		    'image'             =>      $image,
		    'cashBidNum'=>$cashBidNum
		));
	}
	
	public function actionConfirm(){
		$orderId = Yii::app()->request->getParam('orderid');
		$orderInfo = Orders::model()->with(array('oauction','oauction.aoneimage','oauction.aoneimage.imageurl'))->findByPk($orderId);
		$resource=new AuctionResource();
		
		$resource_data=$resource->find("auction_id=".$orderInfo->auction_id." and resource_key= 'image_1'");
		
		if(!empty($resource_data)){
		    
		    $resource_img=new ResourceImg();
		    $resource_img_data=$resource_img->findByPk($resource_data->resource_id);
		    if(!empty($resource_img_data)){
		        $image=$resource_img_data->path;
		
		    }
		
		}
		else{
		    $image = Yii::app()->baseUrl.'/images/no-image.png';
		}
		$amazoncard = array();

		// $shippingInfo = CustomerOrderShippingInfo::model()->find('customer_id = '.Yii::app()->user->id);
		// if(empty($shippingInfo)){
		    $shippingInfo=json_decode($orderInfo->shipping_info);
		// }
		
		    /*
		     *获取用户所花cash bid数目
		     */
		    $bidhistory=new BidHistory();
		    $cashBidNum=$bidhistory->countBySql('
		    SELECT
            	COUNT(ab.id)
            FROM
            	auction_bid_log AS ab
            WHERE
            	ab.customer_id = '.Yii::app()->user->id.'
            AND ab.auction_id = '.$orderInfo->auction_id.'
            AND ab.bid_type = "CASH"
		');
		$this->render('confirm',array(
				'orderInfo'				=>      $orderInfo,
				'shippingInfo'			=>		$shippingInfo,
				'amazoncard'			=>		$amazoncard,
		        'image'                 =>      $image,
		        'cashBidNum'     =>$cashBidNum
		));
	}
	public function actionGetFflDealers(){
	    $zipCode = Yii::app()->request->getParam('zip_code',null);
	    $distance = Yii::app()->request->getParam('distance',null);
	    if (empty($zipCode) || empty($distance)) {
	        echo "zipCode or distance null";die;
// 	        echo '<p class="bg-danger">' . MSG_ZIP_CODE_DISTANCE_EMPTY . '</p>';
	    } else {
	        $xml = simplexml_load_file("./protected/extensions/xml/fflDealers.xml");
	        $zipCodes = $this->get_zipcodes($zipCode, $distance);
	        $data = array();

	        if (count($zipCodes) > 0) {
	            foreach ($xml->FFL as $ffl) {
	                $fflZip = intval($ffl->zip);
	        
	                if (in_array($fflZip, $zipCodes)) {
	                    $data[] = array(
	                        'FFL_Name' => (string) $ffl->FFL_Name,
	                        'FFL_Num' => (string) $ffl->FFL_Num,
	                        'expire' => (string) $ffl->expire,
	                        'address' => (string) $ffl->address,
	                        'city' => (string) $ffl->city,
	                        'state' => (string) $ffl->state,
	                        'zip' => (string) $ffl->zip,
	                        'transfer_fee' => (string) $ffl->transfer_fee,
	                        'notes' => (string) $ffl->notes,
	                        'if_preferred' => (string) $ffl->if_preferred,
	                    );
	                }
	            }
	        }
	        echo json_encode($data);
// 	        if (count($data) > 0) {
// 	            foreach ($data as $dealer) {
// 	                $value = urlencode(serialize($dealer));
// 	                echo '<label class="radio">'
// 	                    . '<input type="radio" style="height:30px;" name="ffl_dealer" value="' . $value . '"> ' . $dealer['FFL_Name'].'<br>'
// 	                        . '<span class="help-block">'
// 	                            . $dealer['address'] . '<br>'
// 	                                . $dealer['zip'] . ', ' . $dealer['city'] . ', ' . $dealer['state'] . '<br>'
// 	                                    . MSG_PREFERRED_DEALER . ': ' . (($dealer['if_preferred']) ? GMSG_YES : GMSG_NO)
// 	                                    . '</span>'
// 	                                        . '</label><br />';
// 	            }            
// 	        } else {
// 	            echo '<p class="bg-danger">' . MSG_NO_FFL_DEALERS_FOUND . '</p>';
// 	        }
	    }
	}
	public function get_zipcodes($zipCode,$distance){
	    
	    $zipcodes = array();
	    
// 	    $zipRow = $db->get_sql_row("SELECT id,latitude,longitude FROM " . DB_PREFIX . "zipcodes
// 		WHERE zipcode = '" . $db->rem_special_chars($zip_code) . "'");
        $zip=new ProbidZipcodes();
        $zipRow=$zip->find('zipcode='.$zipCode);
	    if ($zipRow->id) {
	        $Latitude = $zipRow->latitude;
	        $Longitude = $zipRow->longitude;
	    
	        $zcdRadius = new RadiusAssistant($Latitude, $Longitude, intval($distance));
	        $minLat = $zcdRadius->MinLatitude();
	        $maxLat = $zcdRadius->MaxLatitude();
	        $minLong = $zcdRadius->MinLongitude();
	        $maxLong = $zcdRadius->MaxLongitude();
	    
// 	        $sql_select_zipcodes = $db->query("SELECT * FROM " . DB_PREFIX . "zipcodes
// 	            WHERE latitude >= {$minLat} AND latitude <= {$maxLat} AND longitude >= {$minLong} AND longitude <= {$maxLong}");
	        $sql_select_zipcodes=$zip->findAll('latitude>='.$minLat.' and latitude<='.$maxLat.' and longitude>='.$minLong.' and longitude<='.$maxLong);
// 	        while ($myrow = mysql_fetch_array($sql_select_zipcodes)) {
// 	            $zipcodes[] = $myrow['zipcode'];
// 	        }
            
            foreach ($sql_select_zipcodes as $k=>$v){
                $zipcodes[] =$v->zipcode;
            }
            
	        return $zipcodes;
	    }
	    
// 	    return array($zip_code);
	     
	}
}

